<template>
  <div class="search-list">
    <!-- 折叠标题-包裹检索表单 -->
    <a-collapse
      v-model:activeKey="activeKey"
      :ghost="true">
      <a-collapse-panel
        key="1"
        header="列表页"
      >
      <a-form
        ref="formRef"
        :labelCol="{style:{width:'100px'}}"
        :model="formData">
        <a-row
          :gutter="[50, 20]">
          <a-col :span="8">
            <a-form-item
              label="房源编号"
              name="houseNo">
              <a-input
                v-model:value="formData.houseNo"
                placeholder="请输入房源编号"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="房源面积"
              name="area">
              <a-input
                v-model:value="formData.area"
                placeholder="请输入房源面积"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="小区名称"
              name="communityName">
              <a-input
                v-model:value="formData.communityName"
                placeholder="请输入小区名称"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="录入时间"
              name="loggingDate">
              <a-range-picker
                class="full-width"
                v-model:value="formData.loggingDate"
                valueFormat="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="朝向"
              name="head">
              <a-checkbox-group
                v-model:value="formData.head"
                name="checkboxgroup"
                :options="headStatusOptions" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="楼层"
              name="floor">
              <a-input
                v-model:value="formData.floor"
                placeholder="请输入楼层" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="建筑类型"
              name="houseType">
              <a-select
                ref="select"
                v-model:value="formData.houseType"
                :options="houseTypeOptions"
              ></a-select>
            </a-form-item>
          </a-col>

        </a-row>
        <a-row
          justify="center">
          <a-button type="primary" @click="handleSerch(1)">查询</a-button>
          <a-button  style="margin-left: 10px" @click="handleReset">重置</a-button>
        </a-row>
      </a-form>
    </a-collapse-panel>
  </a-collapse>
  <a-table
    :columns="columns"
    :data-source="listData"
    :pagination="pagination"
    :loading="searchLoading">
    <template #bodyCell="{ column, record, text }">
      <template v-if="column.dataIndex === 'head'">
        <span>{{ convertHeadName(text) }}</span>
      </template>
      <template v-if="column.key === 'action'">
        <a-space>
          <a-button
            type="primary"
            size="small"
            ghost
            @click="handleJumpDetail(record)">详情</a-button>
          <a-button
            type="primary"
            size="small"
            danger
            ghost
            @click="handleDelete(record)">删除</a-button>
        </a-space>
      </template>
    </template>
  </a-table>
</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import type { TableColumnsType } from 'ant-design-vue';
import axios from 'axios';
import{ Form, message, Modal }from "ant-design-vue"
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'

// 设置当前折叠为展开
const activeKey = ref(['1'])
const headStatusOptions = [
  {
    value: '1',
    label: '东',
  },
  {
    value: '2',
    label: '西',
  },
  {
    value: '3',
    label: '南',
  },
  {
    value: '4',
    label: '北',
  },
]
const houseTypeOptions = [
  {
    value: '1',
    label: '板楼',
  },
  {
    value: '2',
    label: '塔楼',
  },
  {
    value: '3',
    label: '平层',
  },
  {
    value: '4',
    label: '别墅',
  },
]

// 表单数据类型定义
interface FormData {
  houseNo: string
  area: number | null
  communityName: string
  head: number[]
  floor: number | null
  houseType: number | null
  loggingDate: string[]
}

// 表单数据
const formData = ref<FormData>({
  houseNo: '',
  area: null,
  communityName: '',
  head: [],
  floor: null,
  houseType: null,
  loggingDate: []
})

// 表单组件实例
const formRef = ref<typeof Form | null>(null)

// 结果列表列配置
const columns:TableColumnsType = [
  {
    title: '房源编号',
    dataIndex: 'houseNo',
    width: 200,
  },
  {
    title: '房源面积',
    dataIndex: 'area',
    width: 150,
  },
  {
    title: '小区名称',
    dataIndex: 'communityName',
    width: 150,
  },
  {
    title: '录入时间',
    dataIndex: 'loggingDate',
    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD')
  },
  {
    title: '朝向',
    dataIndex: 'head',
  },
  {
    title: '楼层',
    dataIndex: 'floor',
  },
  {
    title: '建筑类型',
    dataIndex: 'houseType',
    customRender: ({ text }) => {
      switch (text){
        case 1:
          return '板楼'
          break;
        case 2:
          return '塔楼'
          break;
        case 3:
          return '平层'
          break;
        case 4:
          return '别墅'
          break;
        default:
          return text
      }
    }
  },
  {
    title: '操作',
    key: 'action',
  },
]

interface HouseData {
  houseId: number | string
  houseNo: string
  area: number | null
  communityName: string
  head: number[]
  images:string[]
  floor: number | null
  houseType: number | null
  loggingDate: string[]
}

// 列表数据
const listData = ref([])

// 列表分页默认值
enum PAGINATION_DEFAULT  {
  PAGE = 1,
  PAGE_SIZE = 10,
}

const current = ref(PAGINATION_DEFAULT.PAGE)
const pageSize = ref(PAGINATION_DEFAULT.PAGE_SIZE)
const total = ref<number>(0)

// 列表分页配置
const pagination = computed(() => ({
  current: current.value,
  pageSize: pageSize.value,
  total: total.value,
  showQuickJumper: true,
  showSizeChanger: true,
  showTitle: true,
  pageSizeOptions: [5, 10, 20, 50],
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, size: number) => {
    current.value = page || PAGINATION_DEFAULT.PAGE
    pageSize.value = size || PAGINATION_DEFAULT.PAGE_SIZE
    handleSerch()
  },
}))


/**
 * convertHeadName
 * @description 朝向名称转换
 */
const convertHeadName = (head: []) => {
  let showHead = ''
  head.forEach(item => {
    switch (item){
        case 1:
          showHead += '东'
          break;
        case 2:
          showHead += '西'
          break;
        case 3:
          showHead += '南'
          break;
        case 4:
          showHead += '北'
          break;
        default:
        }
      })
      return showHead
}

const router = useRouter()

/**
 * handleJumpDetail
 * @description 跳转详情页
 * @param record 当前行数据
 */
const handleJumpDetail = (record: HouseData) => {
  router.push({
    path: `/houseDetail/${record.houseId}`,
  })
}

/**
 * handleDelete
 * @description 删除当前行
 * @param index 当前行当前分页索引
 */
const handleDelete = (record: HouseData) => {
  Modal.confirm({
    title: '提示',
    content: '确认删除当前行数据吗？',
    okText: '确认',
    cancelText: '取消',
    centered: true,
    onOk() {
      axios.post('/api/houses/delete', {
       id: record.houseId,
      }).then(() => {
        message.success('删除成功！')
        handleSerch()
      }).catch(() => {
        message.error('请求失败')
      })
    }
  })
}

// 检索加载标识
const searchLoading = ref(false)

/**
 * handleSerch
 * @description 查询数据
 */
 const handleSerch = (page?: number) => {
  current.value = page ?? current.value
  const { houseNo, communityName, area, head, floor, loggingDate, houseType} = formData.value
  const loggingDateStart = loggingDate&&loggingDate.length>1?formData.value.loggingDate[0]:''
  const loggingDateEnd = loggingDate&&loggingDate.length>1?formData.value.loggingDate[0]:''
  searchLoading.value = true
  axios.get('/api/houses', {
    params: {
      houseNo,
      communityName,
      area,
      head,
      loggingDateStart,
      loggingDateEnd,
      floor,
      houseType,
      limit: pageSize.value,
      page: current.value
    }
  }).then((res: { data: { houses: never[]; totalCount: number; }; }) => {
    listData.value = res?.data?.houses || []
    total.value = res?.data?.totalCount
    searchLoading.value = false
  }).catch(() => {
    message.error('请求失败')
    searchLoading.value = false
  })
}
handleSerch()

/**
 * handleReset
 * @description 重置查询
 */
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    handleSerch(1)
  }
}

</script>

<style scoped lang="less">
  .full-width {
    width: 100% !important;
  }
  /** 定制化重置折叠collapse组件部分样式
    * :deep用于穿透当前页面样式作用域（scoped），覆盖引用基础组件默认样式
  */
  :deep(.ant-collapse-item) {
    .ant-collapse-header{
      font-weight: bold;
      font-size: 16px;
      padding: 10px 15px !important;
      background-color: #f2f2f2;
      border-radius: 0 !important;
    }
  }
</style>